package com.lyeducation.social.handler;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyeducation.controllers.dto.system.SysUserDto;
import com.lyeducation.controllers.dto.system.userDetails.UserDetailsImpl;
import com.lyeducation.core.system.SysUserService;
import com.lyeducation.entities.system.SysUserEntity;
import com.lyeducation.security.SecurityConfig;
import com.lyeducation.security.config.SecurityPrincipalContext;
import com.lyeducation.util.jwt.JwtUtil;
import com.lyeducation.util.jwt.JwttokenconfigEnum;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component("ssbAuthenticationSuccessHandler")
public class SsbAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private SysUserService sysUserService;
    //    @Autowired
    //    private ClientDetailsService clientDetailsService;
    //
    //    @Autowired
    //    private AuthorizationServerTokenServices authorizationServerTokenServices;

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.web.authentication.
     * AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.
     * HttpServletRequest, javax.servlet.http.HttpServletResponse,
     * org.springframework.security.core.Authentication)
     */
    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        UserDetailsImpl userDetails = null;
        SysUserEntity sysUserEntity = null;
        try {
            sysUserEntity = (SysUserEntity) SecurityPrincipalContext.getUserDetails();
            userDetails = sysUserEntity.createUserDetailsImpl();
            //        sysUserEntity = sysUserRepository.setLoginUserRoleMenu(sysUserEntity);
            //      paramMap.put("lastLoginIp", sysUserEntity.getLoginIp());

            SecurityConfig.setAuthenticationToSecurityContext(userDetails, request);
        } catch (Exception e) {
            //      userDetails = SecurityPrincipalContext.getUserDetailsImpl();
        }

        sysUserService.updUserParamByLoginSuccess(request);
        response.setContentType("application/json;charset=utf-8");
        paramMap.put(JwttokenconfigEnum.jti.getValue(), userDetails.getId());
        paramMap.put(JwttokenconfigEnum.sub.getValue(), userDetails.getName());
        //    paramMap.put(SysConstants.PASSWORD.getValue(), userDetails.getPassword());
        //    paramMap.put(JwttokenconfigEnum.roles.getValue(), userDetails.getAuthorities());
        String jwtToken = jwtUtil.generateToken(paramMap);
        jwtUtil.addJwtTokenToRedisHash(userDetails.getId(), jwtToken);

        StringBuffer sb = new StringBuffer(jwtUtil.getJwttokenconfigBean().getTokenHead());
        sb.append(jwtToken);
        String jwtHeader = sb.toString();
        System.out.println(jwtHeader);
        response.setHeader(jwtUtil.getJwttokenconfigBean().getHeader(), jwtHeader);
        PrintWriter out = response.getWriter();
        //    ObjectMapper objectMapper = new ObjectMapper();
        paramMap.clear();
        paramMap.put("status", "200");
        if (sysUserEntity != null) {
            SysUserDto sysUserDto = sysUserEntity.createSysUserDto();
            sysUserDto.setId(sysUserEntity.getId());
            paramMap.put("user", sysUserDto);

            //      sb.append(  "{\"status\":\"success\",\"msg\":" +
            // objectMapper.writeValueAsString(sysUserEntity.createSysUserDto()) + "}");
        }
        out.write(JSON.toJSONString(paramMap));
        out.flush();
        out.close();
    }

    private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
            throws IOException {

        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded = null;
        try {
            decoded = Base64.decode(base64Token);
        } catch (IllegalArgumentException e) {
            throw new BadCredentialsException("Failed to decode basic authentication token");
        } catch (Base64DecodingException e) {
            e.printStackTrace();
        }
        String token = new String(decoded, "UTF-8");
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        }
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
}
